﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Ionic.Zlib;
using Ionic.Zip;
using System.IO;

namespace LoLScrape
{
    public partial class frmMain : Form
    {
        private const string DEFAULT_LOL_FOLDER = "C:\\Games\\League of Legends"; //"C:\\Program Files\\Riot Games\\League of Legends\\";

        private const string DB_CONNECT_STRING = "Data Source=D:\\_Projects\\LoLBuilder\\LoLBuilder\\LoLScrape\\LoLDB.sdf";

        private string m_LoLFolder;
        private LoLDB m_DB;

        public frmMain()
        {
            InitializeComponent();

            //Initialize connection to the LoLDB
            m_DB = new LoLDB(DB_CONNECT_STRING);

            //Set Selected Path to default setting
            m_LoLFolder = DEFAULT_LOL_FOLDER;

            LogString("Current Folder: " + m_LoLFolder);
        } //end frmMain (constructor)

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnBrowse_Click(object sender, EventArgs e)
        {
            //Set Selected Path to current LoL folder setting.
            folderBrowser.SelectedPath = m_LoLFolder;

            //Request new folder location using a folder browser window.
            DialogResult rslt = folderBrowser.ShowDialog();

            //If the user selected a folder (and didn't cancel)...
            if (rslt == DialogResult.OK)
            {
                //Set the new Lol folder setting to the selected path.
                m_LoLFolder = folderBrowser.SelectedPath;

                LogString("Current Folder: " + m_LoLFolder);

            }// end if

        } //end btnBrowse_Click

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnScrape_Click(object sender, EventArgs e)
        {
            LogString("Scraping...");
            //Open the HeroPak
            ZipFile file = ZipFile.Read(m_LoLFolder + "\\game\\HeroPak_client.zip");
            
            //Set the size of the progress bar to the number of files in the HeroPak
            progressBar.Maximum = file.Entries.Count - 1;
           
            //Loop through each of the files in the HeroPak, scraping one file at a time
            foreach (ZipEntry entry in file.Entries)
            {
                //Add one step to the progress bar
                progressBar.PerformStep();
                //Only scrape inibin files
                if (entry.FileName.Substring(entry.FileName.Length - 6).Equals("inibin") ||
                    entry.FileName.Substring(entry.FileName.Length - 7).Equals("troybin"))
                {
                    //Scrape this inibin file
                    //LogString(entry.FileName);
                    //CrcCalculatorStream stream = entry.OpenReader();
                    //Dictionary<UInt32, Object> dict = IniBinScraper.Scrape(stream);
                    
                    //All file information has been scraped,  now to parse the file's dictionary
                    //string strAdjustFilename = entry.FileName.Replace('\\', '_');
                    //strAdjustFilename = strAdjustFilename.Replace('/', '_');
            
                    //System.IO.TextWriter myFile = System.IO.File.CreateText("D:\\_____HeroPak\\dict\\" + strAdjustFilename);
                    //object segmentObj;
                    //dict.TryGetValue(0, out segmentObj);
                    //Int16 segmentFlags = (Int16)segmentObj;
                    //myFile.Write("Segments: ");
                    //if ((segmentFlags & 0x0001) != 0) myFile.Write("1, ");
                    //if ((segmentFlags & 0x0002) != 0) myFile.Write("2, ");
                    //if ((segmentFlags & 0x0004) != 0) myFile.Write("3, ");
                    //if ((segmentFlags & 0x0008) != 0) myFile.Write("4, ");
                    //if ((segmentFlags & 0x0010) != 0) myFile.Write("5, ");
                    //if ((segmentFlags & 0x0020) != 0) myFile.Write("6, ");
                    //if ((segmentFlags & 0x0040) != 0) myFile.Write("7, ");
                    //if ((segmentFlags & 0x0080) != 0) myFile.Write("8, ");
                    //if ((segmentFlags & 0x0100) != 0) myFile.Write("9, ");
                    //if ((segmentFlags & 0x0200) != 0) myFile.Write("10, ");
                    //if ((segmentFlags & 0x0400) != 0) myFile.Write("11, ");
                    //if ((segmentFlags & 0x0800) != 0) myFile.Write("12, ");
                    //if ((segmentFlags & 0x1000) != 0) myFile.Write("13, ");
                    //if ((segmentFlags & 0x2000) != 0) myFile.Write("14, ");
                    //if ((segmentFlags & 0x4000) != 0) myFile.Write("15, ");
                    //if ((segmentFlags & 0x8000) != 0) myFile.Write("16, ");
                    //myFile.WriteLine("");

                    //myFile.WriteLine("Key   -  Value");

                    //////////////
                    // Write Bin Key parsed Files
                    /////////////
                    //Dictionary<uint, object>.Enumerator it = dict.GetEnumerator();
                    //
                    //  while (it.MoveNext() == true)
                    //  {
                    //      myFile.WriteLine(it.Current.Key + ": " + it.Current.Value);   
                    //  } //end while
                    //
                    //myFile.Close();

                    ////////////////
                    //  Create Initial Database
                    ///////////////
                    //Dictionary<uint, object>.Enumerator it = dict.GetEnumerator();
                    //
                    //while (it.MoveNext() == true)
                    //{
                    //    UpdateInsertBinKeyRow(it.Current.Key, "UNKNOWN", it.Current.Value.ToString(), strAdjustFilename);
                    //} //end while

                } //end if
            } //end foreach
            LogString("... DONE! ");

            

            //C:\Games\League of Legends\game\DATA\Menu\fontconfig_en_US.txt
        } //end btnBrowse_Click

        private void LogString(string str)
        {
            string strTimestamp = DateTime.Now.ToLongTimeString();

            txtLog.AppendText(strTimestamp + ": " + str + "\n");
            txtLog.ScrollToCaret();
        } //end LogString

        private void UpdateInsertBinKeyRow(uint intBinKeyId, string strValue, string strSampleValue, string strFilename)
        {          
            TblBinKeys row;

            //attempt to retrieve an existing row using the given BinKey id.
            try
            {
                row = m_DB.TblBinKeys.Single(r => r.ColBinKeyID == intBinKeyId);
            } //end try
            catch
            {
                //The row does not yet exist within the BinKey table, insert the new row
                row = new TblBinKeys();
                m_DB.TblBinKeys.InsertOnSubmit(row);
            } //end try

            row.ColBinKeyID = intBinKeyId;
            row.ColKeyName = strValue;
            //row.ColSampleData = ( strSampleValue.Length >= 100 )? strSampleValue.Substring(0, 99) : strSampleValue;
            //row.ColSampleFile = ( strFilename.Length >= 100 )? strFilename.Substring(0, 99) : strFilename;

            m_DB.SubmitChanges();
            
        } //end UpdateInsertBinKeyRow

        private void btnTest_Click(object sender, EventArgs e)
        {
            System.IO.TextReader myFile = System.IO.File.OpenText("D:\\_____HeroPak\\inibin\\KeysToNames.txt");

            string strLine;
            string[] strArray;
            char[] strSep = { ' ' };
            try
            {
                while ( (strLine = myFile.ReadLine()) != null )
                {
                    strArray = strLine.Split(strSep);
                    UInt32 intKey = UInt32.Parse(strArray[0]);
                    UpdateInsertBinKeyRow(intKey, strArray[1], "", "");
                }
            }
            catch (IOException)
            {
                //DONE
            }

            myFile.Close();

        } //end btnTest_Click

        private void vwManifestTree_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
        {
            if (e.Node.ImageIndex == 1 || e.Node.IsExpanded)
            {
                e.Node.Collapse();
                e.Node.ImageIndex = 0;
                e.Node.SelectedImageIndex = 0;
            } //end if
            else
            {
                e.Node.Expand();
                e.Node.ImageIndex = 1;
                e.Node.SelectedImageIndex = 1;
            } //end else
        } //end vwManifestTree_NodeMouseClick

    } //end frmMain

} //end LoLScrape
